import 'package:flutter/material.dart';
import 'package:visibility_detector/visibility_detector.dart';

class VisibilityChangeWidget extends StatefulWidget {
  const VisibilityChangeWidget({
    super.key,
    required this.visibilityKey,
    required this.child,
    this.isListenerAppLifecycleState = true,
    this.onVisibility,
    this.onHide,
  });

  final Key visibilityKey;
  final bool isListenerAppLifecycleState;
  final Widget child;
  final VoidCallback? onVisibility;
  final VoidCallback? onHide;

  @override
  State<StatefulWidget> createState() {
    return _VisibilityChangeWidgetState();
  }
}

class _VisibilityChangeWidgetState extends State<VisibilityChangeWidget>
    with WidgetsBindingObserver {
  var isFirstVisibility = true;
  bool? isVisibility;

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (widget.isListenerAppLifecycleState) {
      if (state == AppLifecycleState.resumed) {
        if (!isFirstVisibility && isVisibility == true) {
          widget.onVisibility?.call();
        }
      } else if (state == AppLifecycleState.paused ||
          state == AppLifecycleState.inactive) {
        widget.onHide?.call();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: widget.visibilityKey,
      onVisibilityChanged: (visibilityInfo) {
        if (visibilityInfo.visibleFraction != 0.0) {
          if (isFirstVisibility) {
            isFirstVisibility = false;
            isVisibility = true;
          } else {
            if (isVisibility != true) {
              isVisibility = true;
              widget.onVisibility?.call();
            }
          }
        } else {
          isVisibility = false;
          widget.onHide?.call();
        }
      },
      child: widget.child,
    );
  }
}
